package com.ruoyi.chat.websocket;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.chat.domain.ChatSession;
import com.ruoyi.chat.domain.MessageBody;
import com.ruoyi.chat.service.IChatRecordService;
import com.ruoyi.chat.service.IChatSessionService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.websocket.SemaphoreUtils;
import com.ruoyi.framework.websocket.WebSocketUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 * 
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static final Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    @Autowired
    private static IChatSessionService chatSessionService;

    private static IChatRecordService chatRecordService;

    private static SiliconFlowApiClient siliconFlowApiClient;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception
    {
        if (chatSessionService == null) {
            chatSessionService = SpringContextHolder.getBean(IChatSessionService.class);
        }
        if (chatRecordService == null) {
            chatRecordService = SpringContextHolder.getBean(IChatRecordService.class);
        }

        if (siliconFlowApiClient == null) {
            siliconFlowApiClient = SpringContextHolder.getBean(SiliconFlowApiClient.class);
        }

        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            // 添加用户
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());

            ChatSession chatSession = new ChatSession();
            chatSession.setCreateBy(SecurityUtils.getUsername());
            String chatSessionId = DateUtils.dateTimeNow()+ UUID.get4UUID();
            chatSession.setId(chatSessionId);
            chatSession.setStatus("0");
            chatSessionService.insertChatSession(chatSession);

            MessageBody messageBody = new MessageBody();
            messageBody.setMessage("系统消息：连接成功");
            messageBody.setSessionId(chatSessionId);
            messageBody.setUserName(SecurityUtils.getUsername());

            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(messageBody));
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);

        updateChatSession();
    }

    private void updateChatSession() {
        ChatSession chatSession = new ChatSession();
        chatSession.setCreateBy(SecurityUtils.getUsername());
        ChatSession chatSessionResult = chatSessionService.selectChatSessionByUserName(chatSession.getCreateBy());
        if(chatSessionResult!=null && !"1".equals(chatSessionResult.getStatus())){
            chatSessionResult.setStatus("1");
            chatSessionService.updateChatSession(chatSession);
        }
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);

        updateChatSession();
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        System.out.println("接收到消息：" + message);
        //String msg = message.replace("你", "我").replace("吗", "");
        //WebSocketUsers.sendMessageToUserByText(session, msg);
        siliconFlowApiClient.funcationCall(message,session);
    }
}
